package mahongyuan.com.studentsystem;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import reflash.Chart;

public class HomeFragment extends Fragment
{
	private PieChart mChart;

	Chart chart;
	private View myView;
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)

	{
//		if (myView != null) {
//			ViewGroup parent = (ViewGroup) myView.getParent();
//			if (parent != null) {
//				parent.removeView(myView);
//			}
//			Log.i("tag","1");
//			mChart = (PieChart) myView.findViewById(R.id.spread_pie_chart);
//			PieData mPieData = getPieData(4, 100);
//			showChart(mChart, mPieData);
//			return myView;
//		}
		Log.i("tag","chart init");
		myView = inflater.inflate(R.layout.tab01, container, false);
		mChart = (PieChart) myView.findViewById(R.id.spread_pie_chart);
//		PieData mPieData = getPieData(4, 100);
//		showChart(mChart, mPieData);

		this.request();
		return myView;
	}

	private void showChart(PieChart pieChart, PieData pieData) {
		pieChart.setHoleColorTransparent(true);

		pieChart.setHoleRadius(60f);  //半径
		pieChart.setTransparentCircleRadius(64f); // 半透明圈
		//pieChart.setHoleRadius(0)  //实心圆

		pieChart.setDescription("测试饼状图");

		// mChart.setDrawYValues(true);
		pieChart.setDrawCenterText(true);  //饼状图中间可以添加文字

		pieChart.setDrawHoleEnabled(true);

		pieChart.setRotationAngle(90); // 初始旋转角度

		// draws the corresponding description value into the slice
		// mChart.setDrawXValues(true);

		// enable rotation of the chart by touch
		pieChart.setRotationEnabled(true); // 可以手动旋转

		// display percentage values
		pieChart.setUsePercentValues(true);  //显示成百分比
		// mChart.setUnit(" €");
		// mChart.setDrawUnitsInChart(true);

		// add a selection listener
//      mChart.setOnChartValueSelectedListener(this);
		// mChart.setTouchEnabled(false);

//      mChart.setOnAnimationListener(this);

		pieChart.setCenterText("男女比例");  //饼状图中间的文字

		//设置数据
		pieChart.setData(pieData);

		// undo all highlights
//      pieChart.highlightValues(null);
//      pieChart.invalidate();

		Legend mLegend = pieChart.getLegend();  //设置比例图
		mLegend.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);  //最右边显示
//      mLegend.setForm(LegendForm.LINE);  //设置比例图的形状，默认是方形
		mLegend.setXEntrySpace(7f);
		mLegend.setYEntrySpace(5f);

		pieChart.animateXY(1000, 1000);  //设置动画
		// mChart.spin(2000, 0, 360);
	}

	/**
	 *
	 * @param count 分成几部分
	 * @param range
	 */
	private PieData getPieData(int count, float range) {

		ArrayList<String> xValues = new ArrayList<String>();  //xVals用来表示每个饼块上的内容

		for (int i = 0; i < count; i++) {
			switch (i){
				case(0):
					xValues.add("女生" );
					break;
				case(1):
					xValues.add("男生" );
					break;
			}
//					xValues.add("女生" );  //饼块上显示成Quarterly1, Quarterly2, Quarterly3, Quarterly4
		}

		ArrayList<Entry> yValues = new ArrayList<Entry>();  //yVals用来表示封装每个饼块的实际数据

		// 饼图数据
		/**
		 * 将一个饼形图分成四部分， 四部分的数值比例为14:14:34:38
		 * 所以 14代表的百分比就是14%
		 */

		float quarterly1 = Float.parseFloat(chart.getFemale());
		float quarterly2 = Float.parseFloat(chart.getMale());
//		float quarterly3 = 34;
//		float quarterly4 = 38;

		yValues.add(new Entry(quarterly1, 0));
		yValues.add(new Entry(quarterly2, 1));
//		yValues.add(new Entry(quarterly3, 2));
//		yValues.add(new Entry(quarterly4, 3));

		//y轴的集合
		PieDataSet pieDataSet = new PieDataSet(yValues, "总人数："+chart.getTotal()/*显示在比例图上*/);
		pieDataSet.setSliceSpace(0f); //设置个饼状图之间的距离

		ArrayList<Integer> colors = new ArrayList<Integer>();

		// 饼图颜色
		colors.add(Color.rgb(205, 205, 205));
		colors.add(Color.rgb(114, 188, 223));
//		colors.add(Color.rgb(255, 123, 124));
//		colors.add(Color.rgb(57, 135, 200));

		pieDataSet.setColors(colors);

		DisplayMetrics metrics = getResources().getDisplayMetrics();
		float px = 5 * (metrics.densityDpi / 160f);
		pieDataSet.setSelectionShift(px); // 选中态多出的长度

		PieData pieData = new PieData(xValues, pieDataSet);

		return pieData;
	}

	public void request() {
		//步骤4:创建Retrofit对象
		//创建okHttpClient对象
		OkHttpClient mOkHttpClient = new OkHttpClient();
		//创建一个Request
		final Request request = new Request.Builder()
				.url("http://10.0.2.2/stuServer/api/chart" )
				.build();
		//new call
		Call call = mOkHttpClient.newCall(request);
		//请求加入调度
		call.enqueue(new Callback()
		{
			@Override
			public void onFailure(Call call, IOException e) {
				Log.i("kwwl","获取数据失败了");
			}
			@Override
			public void onResponse(Call call, Response response) throws IOException {
				if(response.isSuccessful()){//回调的方法执行在子线程。
					Log.i("kwwl","获取chart数据成功了");

					//Log.i("kwwl","response.code()=="+response.code());
					String responseData = response.body().string();
					System.out.println(responseData);

					//Log.i(TAG, response.body().string());
					parseJSONWithGSON(responseData);

                    HomeFragment.this.myView.post(new Runnable() {
                        public void run() {
							PieData mPieData = getPieData(4, 100);
							showChart(mChart, mPieData);
                        }
                    });
				}
			}
		});
	}

	private void parseJSONWithGSON(String jsonData) {
		Gson gson = new Gson();
		chart = gson.fromJson(jsonData, new TypeToken<Chart>() {
		}.getType());

		System.out.println("pares:"+chart.toString());

//		HomeFragment.this.myview.post(new Runnable() {
//			public void run() {
//				HomeFragment.this.render();
//			}
//		});
	}


}
